package com.egao.common.module.recommendation.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.egao.common.component.minio.config.MinioBucket;
import com.egao.common.core.exception.ParameterException;
import com.egao.common.core.web.JsonResult;
import com.egao.common.core.web.PageParam;
import com.egao.common.core.web.PageResult;
import com.egao.common.manage.CommonRefService;
import com.egao.common.module.recommendation.constants.RecommendationConstants;
import com.egao.common.module.recommendation.entity.GraduateEmploymentCertification;
import com.egao.common.module.recommendation.entity.RecommendationGraduateEmployment;
import com.egao.common.module.recommendation.entity.RecommendationUndergraduateEmployment;
import com.egao.common.module.recommendation.entity.vo.RecommendationAuditParam;
import com.egao.common.module.recommendation.entity.vo.RecommendationGraduateEmploymentVo;
import com.egao.common.module.recommendation.entity.vo.RecommendationListVo;
import com.egao.common.module.recommendation.entity.vo.RecommendationUndergraduateEmploymentVo;
import com.egao.common.module.recommendation.mapper.RecommendationGraduateEmploymentMapper;
import com.egao.common.module.recommendation.service.IRecommendationGraduateEmploymentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.egao.common.module.student.entity.Student;
import com.egao.common.module.student.entity.StudentInfo;
import com.egao.common.module.student.mapper.StudentInfoMapper;
import com.egao.common.module.student.mapper.StudentMapper;
import com.egao.common.module.student.service.StudentInfoService;
import com.egao.common.module.student.service.StudentService;
import com.egao.common.module.system.constants.UserConstants;
import com.egao.common.module.system.entity.College;
import com.egao.common.module.system.entity.Major;
import com.egao.common.module.system.entity.User;
import com.egao.common.module.system.mapper.CollegeMapper;
import com.egao.common.module.system.mapper.MajorMapper;
import com.egao.common.module.system.mapper.UserMapper;
import com.egao.common.module.system.service.DictService;
import com.itextpdf.io.font.PdfEncodings;
import com.itextpdf.io.image.ImageData;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.borders.Border;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Image;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.properties.*;
import com.itextpdf.text.Utilities;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.egao.common.module.recommendation.constants.RecommendationConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ld
 * @since 2025-04-02
 */
@Service
public class RecommendationGraduateEmploymentServiceImpl extends ServiceImpl<RecommendationGraduateEmploymentMapper, RecommendationGraduateEmployment> implements IRecommendationGraduateEmploymentService {

    @Autowired
    private StudentInfoService studentInfoService;

    @Autowired
    private DictService dictService;

    @Autowired
    private CollegeMapper collegeMapper;

    @Autowired
    private MajorMapper majorMapper;

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private StudentInfoMapper studentInfoMapper;

    @Autowired
    private StudentService studentService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private CommonRefService refService;

    @Value("${minio.recmdDir}")
    private String recmdDir;
    @Value("${minio.endpoint}")
    private String endpoint;
    @Value("${pdf.font}")
    private String pdfFont;
    @Value("${pdf.picture}")
    private String pdfPicture;

    @Override
    public PageResult<RecommendationListVo> list(PageParam<RecommendationGraduateEmployment> page) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User curUser = (User) authentication.getPrincipal();
        QueryWrapper<RecommendationGraduateEmployment> wrapper = new QueryWrapper<>();
        wrapper.ge(page.getPageData().get("beginDate") != null, "update_time", page.getPageData().get("beginDate"));
        wrapper.lt(page.getPageData().get("endDate") != null, "update_time", page.getPageData().get("endDate"));
        wrapper.eq(page.getPageData().get("status") != null, "status", page.getPageData().get("status"));
        wrapper.orderByAsc("update_time");
        // 学生只能查看自己的记录
        Student student = studentMapper.selectOne(new QueryWrapper<Student>().eq("user_id", curUser.getUserId()));
        if (student != null) {
            wrapper.eq("user_id", student.getUserId());
            return new PageResult<>(models2vos(this.page(page, wrapper).getRecords()), page.getTotal());
        }
        //教师逻辑，仅查询本院学生
        User teacher = userMapper.selectById(curUser.getUserId());
        wrapper.eq(curUser.getDegreeScope() != null && !UserConstants.DEGREE_SCOPE_ALL.equals(curUser.getDegreeScope()),
                "degree", curUser.getDegreeScope());
        wrapper.eq("xybm", teacher.getCollegeCode());
        wrapper.ne("status", RecommendationConstants.RECOMMENDATION_STATUS_INIT);
        //处理筛选条件
        if (page.getPageData().get("con") != null && StrUtil.isNotBlank((String) page.getPageData().get("con"))) {
            wrapper.and(w -> w.like("xh", page.getPageData().get("con")).or().like("xm", page.getPageData().get("con")));
        }
        return new PageResult<>(models2vos(this.page(page, wrapper).getRecords()), page.getTotal());
    }

    private List<RecommendationListVo> models2vos(List<RecommendationGraduateEmployment> models) {
        LinkedList<RecommendationListVo> vos = new LinkedList<>();
        List<String> codes = new LinkedList<>();
        models.forEach(model -> {
            RecommendationListVo vo = new RecommendationListVo();
            BeanUtils.copyProperties(model, vo);
            if (StrUtil.isNotBlank(model.getCollegeCode()) && !codes.contains(model.getCollegeCode())) {
                codes.add(model.getCollegeCode());
            }
            vos.add(vo);
        });
        Map<String, College> map = refService.refCollege(codes);
        vos.forEach(vo -> {
            if (map.get(vo.getCollegeCode()) != null) {
                vo.setCollegeName(map.get(vo.getCollegeCode()).getName());
            }
        });
        return vos;
    }


    @Override
    public JsonResult read(Integer id) {
        if (id == null) {
            throw new ParameterException("参数对象id为空");
        }

        RecommendationGraduateEmployment model = baseMapper.selectById(id);
        if(model == null){
            throw new ParameterException("该推荐表已删除！");
        }

        Integer userId = model.getUserId();
        Student student = studentService.getByUserId(userId);
        if (student == null) {
            throw new ParameterException("学生信息异常");
        }
        StudentInfo studentInfo = studentInfoService.getByStudentId(student.getId());

        RecommendationGraduateEmploymentVo vo = new RecommendationGraduateEmploymentVo();
        BeanUtils.copyProperties(student, vo);
        if (studentInfo != null) {
            BeanUtils.copyProperties(studentInfo, vo);
        }
        BeanUtils.copyProperties(model, vo);

        College college = collegeMapper.selectOne(new QueryWrapper<College>().eq("code", student.getCollegeCode()));
        vo.setCollegeName(college.getName());

        Major major = majorMapper.selectOne(new QueryWrapper<Major>().eq("code", student.getMajorCode()));
        vo.setMajorName(major.getName());

        vo.setXb(dictService.cacheLabel(RecommendationConstants.XB, student.getXb()));
        vo.setXl(dictService.cacheLabel(RecommendationConstants.XL, student.getXl()));
        vo.setZzmm(dictService.cacheLabel(RecommendationConstants.ZZMM, student.getZzmm()));
        vo.setMz(dictService.cacheLabel(RecommendationConstants.MZ, student.getMz()));
        vo.setSyszd(dictService.cacheLabel(RecommendationConstants.SYSZD, student.getSyszd()));
        vo.setHyzk(dictService.cacheLabel(RecommendationConstants.HYZK, studentInfo.getHyzk()));
        return JsonResult.ok().setData(vo);
    }

    @Override
    public JsonResult read(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User curUser = (User) authentication.getPrincipal();
        QueryWrapper<RecommendationGraduateEmployment> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", curUser.getUserId());
        RecommendationGraduateEmployment model = baseMapper.selectOne(wrapper);

        if (model == null) {
            RecommendationGraduateEmploymentVo vo = new RecommendationGraduateEmploymentVo();

            Student student = studentMapper.selectOne(new QueryWrapper<Student>().eq("user_id", curUser.getUserId()));
            vo.setXm(student.getXm());
            vo.setXh(student.getXh());
            vo.setXb(dictService.cacheLabel(RecommendationConstants.XB, student.getXb()));
            vo.setDegree(student.getDegree());
            vo.setYearId(student.getYearId());
            vo.setEmail(student.getEmail());
            College college = collegeMapper.selectOne(new QueryWrapper<College>().eq("code", student.getCollegeCode()));
            vo.setCollegeName(college.getName());
            Major major = majorMapper.selectOne(new QueryWrapper<Major>().eq("code", student.getMajorCode()));
            vo.setMajorName(major.getName());
            vo.setCsrq(student.getCsrq());
            vo.setZzmm(dictService.cacheLabel(RecommendationConstants.ZZMM, student.getZzmm()));
            vo.setMz(dictService.cacheLabel(RecommendationConstants.MZ, student.getMz()));
            vo.setSyszd(dictService.cacheLabel(RecommendationConstants.SYSZD, student.getSyszd()));

            StudentInfo studentInfo = studentInfoMapper.selectOne(new QueryWrapper<StudentInfo>().eq("user_id", curUser.getUserId()));
            vo.setYjfx(studentInfo.getYjfx());
            vo.setHyzk(dictService.cacheLabel(RecommendationConstants.HYZK, studentInfo.getHyzk()));
            return JsonResult.ok().setData(vo);
        }
        return read(model.getId());
    }

    @Override
    @Transactional
    public JsonResult add(RecommendationGraduateEmployment model) {
        if (model == null){
            throw new ParameterException("参数对象为空");
        }
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User curUser = (User) authentication.getPrincipal();

        QueryWrapper<RecommendationGraduateEmployment> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", curUser.getUserId());

        RecommendationGraduateEmployment tmp = baseMapper.selectOne(wrapper);
        model.setUserId(curUser.getUserId());
        model.setCollegeCode(curUser.getCollegeCode());
        Student student = studentMapper.selectOne(new QueryWrapper<Student>().eq("user_id", curUser.getUserId()));
        model.setXh(student.getXh());
        model.setXm(student.getXm());
        model.setDegree(student.getDegree());
        model.setUpdateTime(new Date());
        if (tmp == null){
            model.setStatus(RecommendationConstants.RECOMMENDATION_STATUS_INIT);
            model.setCreateTime(model.getUpdateTime());
            baseMapper.insert(model);
        }else {
            if (tmp.getStatus().equals(RecommendationConstants.RECOMMENDATION_STATUS_INIT)
                    || tmp.getStatus().equals(RecommendationConstants.RECOMMENDATION_STATUS_REJECT)) {
                model.setId(tmp.getId());
                model.setCreateTime(tmp.getCreateTime());
                baseMapper.updateById(model);
            } else {
                return JsonResult.error("已有数据进入审核流程，请勿重复添加");
            }
        }
        return read(model.getId());
    }

    @Override
    public JsonResult submit(Integer id) {
        if (id == null) {
            throw new ParameterException("参数对象id为空");
        }
        RecommendationGraduateEmployment model = baseMapper.selectById(id);
        if (model.getStatus().equals(RecommendationConstants.RECOMMENDATION_STATUS_INIT)
                || model.getStatus().equals(RecommendationConstants.RECOMMENDATION_STATUS_REJECT)) {
            model.setStatus(RecommendationConstants.RECOMMENDATION_STATUS_SUBMIT);
            model.setUpdateTime(new Date());
            baseMapper.updateById(model);
            return read(model.getId());
        }
        return JsonResult.error("已提交,请勿重复提交");
    }

    @Override
    public JsonResult update(RecommendationGraduateEmployment model) {
        if (model == null){
            throw new ParameterException("参数对象为空");
        }
        if (model.getId() == null){
            throw new ParameterException("参数对象id为空");
        }
        RecommendationGraduateEmployment tmp = baseMapper.selectById(model.getId());
        if (tmp.getStatus().equals(RecommendationConstants.RECOMMENDATION_STATUS_INIT)
                || tmp.getStatus().equals(RecommendationConstants.RECOMMENDATION_STATUS_REJECT)){
            model.setUpdateTime(new Date());
            baseMapper.updateById(model);
            return read(model.getId());
        }
        return JsonResult.error("已提交，暂时不能保存修改");
    }

    @Override
    public JsonResult audit(RecommendationAuditParam param) {
        if (param == null) {
            throw new ParameterException("参数对象为空");
        }

        if (param.getId() == null) {
            throw new ParameterException("参数对象id为空");
        }

        RecommendationGraduateEmployment model = baseMapper.selectById(param.getId());
        if (!model.getStatus().equals(RecommendationConstants.RECOMMENDATION_STATUS_SUBMIT)) {
            throw new ParameterException("当前数据状态不满足审核条件");
        }
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User curUser = (User) authentication.getPrincipal();
        model.setReviewUser(curUser.getUserId());
        model.setStatus(param.getStatus());
        model.setReviewComment(param.getComment());
        model.setCollegePhone(param.getCollegePhone());
        model.setReviewTime(new Date());
        model.setSchoolRecommendationTime(new Date());
        baseMapper.updateById(model);

        return read(model.getId());
    }

    @Override
    public JsonResult delete(Integer[] ids) {
        if (ids == null){
            throw new ParameterException("参数对象为空");
        }

        if (ids.length > 0){
            baseMapper.deleteBatchIds(Arrays.asList(ids));
        }
        return JsonResult.ok("删除成功");
    }

    @Override
    public JsonResult export(Integer id, HttpServletResponse response) throws IOException {
        RecommendationGraduateEmploymentVo vo = (RecommendationGraduateEmploymentVo) read(id).getData();
        String url = endpoint + "/" + MinioBucket.MINIO_RECMD + "/" + RecommendationConstants.REC_GRADUATE_EMPL + "/" + vo.getUserId() + ".pdf";
        String path = recmdDir + File.separator + RecommendationConstants.REC_GRADUATE_EMPL + File.separator + vo.getUserId() + ".pdf";
        if (!vo.getStatus().equals(RecommendationConstants.RECOMMENDATION_STATUS_PASS)) {
            return JsonResult.error("未通过审核，无法导出");
        }
        if (vo.getGenFlag().equals(RecommendationConstants.GEN_FLAG_NO)) {
            try {

                PdfWriter writer = new PdfWriter(new FileOutputStream(path));
                PdfDocument pdf = new PdfDocument(writer);
                Document document = new Document(pdf);
                addTableToDocument(document, vo);
                document.close();
                writer.close();
                UpdateWrapper<RecommendationGraduateEmployment> wrapper = new UpdateWrapper<>();
                wrapper.eq("id", vo.getId()).set("gen_flag", RecommendationConstants.GEN_FLAG_YES)
                        .set("rpt_url", url);
                baseMapper.update(null, wrapper);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition",
                "attachment; filename=" + RecommendationConstants.REC_GRADUATE_EMPL + ".pdf");
        File file = new File(path);
        byte[] fileBytes = Files.readAllBytes(file.toPath());
        try (OutputStream os = response.getOutputStream()) {
            os.write(fileBytes);
        }
        return JsonResult.ok(url);
    }

    private void addTableToDocument(Document document, RecommendationGraduateEmploymentVo vo) {
        try {

            String fontUrl = pdfFont + "simsun.ttc,1";
            PdfFont font = PdfFontFactory.createFont(
                    fontUrl,
                    PdfEncodings.IDENTITY_H,                 // 编码
                    PdfFontFactory.EmbeddingStrategy.FORCE_EMBEDDED  // 嵌入策略
            );

            float[] columnWides = {1, 1, 1, 1, 1, 1, 1, 1};     //分为8列，每列的比例相同
            Table table = new Table(UnitValue.createPercentArray(columnWides)).setFont(font);
            table.setWidth(UnitValue.createPercentValue(100));  //设置表格占页面宽度的100%（自适应）
            table.setMinHeight(UnitValue.createPercentValue(100));
            table.setTextAlignment(TextAlignment.CENTER);

            //表头
            ImageData sealData = ImageDataFactory.create(pdfPicture + "schoolPhoto.png");
            Image schoolPhoto = new Image(sealData);
            Cell schoolPhotoCell = new Cell(1, 3).add(schoolPhoto.setAutoScale(true)).setBorder(Border.NO_BORDER).setHeight(40).setVerticalAlignment(VerticalAlignment.MIDDLE);     //rowspan: 1, colspan: 2 表示占一行两列的单元格
            Cell title = new Cell(1, 5).add(new Paragraph(vo.getYearId() + "届毕业研究生就业推荐表")).setFontSize(20).setBold().setBorder(Border.NO_BORDER).setHeight(40).setVerticalAlignment(VerticalAlignment.MIDDLE);
            table.addCell(schoolPhotoCell);
            table.addCell(title);

            // 第1行
            Cell collegeNameLevelLabel = new Cell().add(new Paragraph("学院")).setBold().setHeight(25).setVerticalAlignment(VerticalAlignment.MIDDLE);
            Cell collegeNameLevelValue = new Cell(1, 2).add(new Paragraph(vo.getCollegeName())).setHeight(25).setVerticalAlignment(VerticalAlignment.MIDDLE);
            table.addCell(collegeNameLevelLabel);
            table.addCell(collegeNameLevelValue);
            Cell majorNameLevelLabel = new Cell().add(new Paragraph("专业")).setBold().setHeight(25).setHeight(25).setVerticalAlignment(VerticalAlignment.MIDDLE);
            Cell majorNameLevelValue = new Cell(1, 2).add(new Paragraph(vo.getMajorName()).setHeight(25).setVerticalAlignment(VerticalAlignment.MIDDLE));
            table.addCell(majorNameLevelLabel);
            table.addCell(majorNameLevelValue);

            Cell photoCell = new Cell(5, 2).setWidth(100);
            if (vo.getPhoto() != null) {
                ImageData photoData = ImageDataFactory.create(vo.getPhoto());
                Image photo = new Image(photoData);
                photo.scaleToFit(100, 120); //可能要改成150,180
                photo.setTextAlignment(TextAlignment.CENTER);
                photoCell.add(photo).setVerticalAlignment(VerticalAlignment.MIDDLE).setTextAlignment(TextAlignment.CENTER);
            }
            table.addCell(photoCell);

            // 第2行
            Cell xmLevelLabel = new Cell().add(new Paragraph("姓名")).setBold().setHeight(25).setVerticalAlignment(VerticalAlignment.MIDDLE);
            Cell xmLevelValue = new Cell(1, 2).add(new Paragraph(vo.getXm()).setHeight(25).setVerticalAlignment(VerticalAlignment.MIDDLE));
            table.addCell(xmLevelLabel);
            table.addCell(xmLevelValue);
            String yjfx = vo.getYjfx() != null? vo.getYjfx() : "无";
            Cell yjfxLabel = new Cell().add(new Paragraph("研究方向")).setBold().setHeight(25).setVerticalAlignment(VerticalAlignment.MIDDLE);
            Cell yjfxValue = new Cell(1, 2).add(new Paragraph(yjfx).setHeight(25).setVerticalAlignment(VerticalAlignment.MIDDLE));
            table.addCell(yjfxLabel);
            table.addCell(yjfxValue);

            // 第3行
            SimpleDateFormat formatSdf = new SimpleDateFormat("yyyyMM");
            Cell csrqLabel = new Cell().add(new Paragraph("出生年月")).setBold().setHeight(25).setVerticalAlignment(VerticalAlignment.MIDDLE);
            Cell csrqValue = new Cell(1, 2).add(new Paragraph(formatSdf.format(vo.getCsrq())).setHeight(25).setVerticalAlignment(VerticalAlignment.MIDDLE));
            table.addCell(csrqLabel);
            table.addCell(csrqValue);
            Cell rxsjLabel = new Cell().add(new Paragraph("入学时间")).setBold().setHeight(25).setVerticalAlignment(VerticalAlignment.MIDDLE);
            Cell rxsjValue = new Cell(1, 2).add(new Paragraph(formatSdf.format(vo.getRxsj())).setHeight(25).setVerticalAlignment(VerticalAlignment.MIDDLE));
            table.addCell(rxsjLabel);
            table.addCell(rxsjValue);

            // 第4行
            Cell xbLabel = new Cell().add(new Paragraph("性别")).setBold().setHeight(25).setVerticalAlignment(VerticalAlignment.MIDDLE);
            Cell xbValue = new Cell(1,2).add(new Paragraph(vo.getXb())).setHeight(25).setVerticalAlignment(VerticalAlignment.MIDDLE);
            table.addCell(xbLabel);
            table.addCell(xbValue);
            Cell bxsjLabel = new Cell().add(new Paragraph("毕业时间")).setBold().setHeight(25).setVerticalAlignment(VerticalAlignment.MIDDLE);
            Cell bxsjValue = new Cell(1, 2).add(new Paragraph(formatSdf.format(vo.getBysj())).setHeight(25).setVerticalAlignment(VerticalAlignment.MIDDLE));
            table.addCell(bxsjLabel);
            table.addCell(bxsjValue);

            // 第5行
            Cell mzLabel = new Cell().add(new Paragraph("民族")).setBold().setVerticalAlignment(VerticalAlignment.MIDDLE);
            Cell mzValue = new Cell(1,2).add(new Paragraph(vo.getMz())).setVerticalAlignment(VerticalAlignment.MIDDLE);
            table.addCell(mzLabel);
            table.addCell(mzValue);
            Cell computerRankLevelLabel = new Cell().add(new Paragraph("计算机等级水平")).setBold().setVerticalAlignment(VerticalAlignment.MIDDLE);
            Cell computerRankLevelValue = new Cell(1,2).add(new Paragraph(vo.getComputerRankLevel())).setVerticalAlignment(VerticalAlignment.MIDDLE);
            table.addCell(computerRankLevelLabel);
            table.addCell(computerRankLevelValue);

            // 第6行
            Cell zzmmlLabel = new Cell().add(new Paragraph("政治面貌")).setBold().setVerticalAlignment(VerticalAlignment.MIDDLE);
            Cell zzmmValue = new Cell(1,2).add(new Paragraph(vo.getZzmm())).setVerticalAlignment(VerticalAlignment.MIDDLE);
            table.addCell(zzmmlLabel);
            table.addCell(zzmmValue);
            Cell foreignLanguageLevelLabel = new Cell().add(new Paragraph("外语等级水平")).setBold().setVerticalAlignment(VerticalAlignment.MIDDLE);
            Cell foreignLanguageLevelValue = new Cell(1, 4).add(new Paragraph(vo.getForeignLanguageLevel())).setVerticalAlignment(VerticalAlignment.MIDDLE);
            table.addCell(foreignLanguageLevelLabel);
            table.addCell(foreignLanguageLevelValue);

            //第7行
            Cell hyzklLabel = new Cell().add(new Paragraph("婚姻状况")).setBold().setHeight(25).setVerticalAlignment(VerticalAlignment.MIDDLE);
            Cell hyzkValue = new Cell(1,2).add(new Paragraph(vo.getHyzk())).setVerticalAlignment(VerticalAlignment.MIDDLE);
            table.addCell(hyzklLabel);
            table.addCell(hyzkValue);
//            addCellTOTable(table, "婚姻状况", vo.getHyzk(), font);
            Cell sydLabel = new Cell().add(new Paragraph("生源地")).setBold().setHeight(25).setVerticalAlignment(VerticalAlignment.MIDDLE);
            Cell sydValue = new Cell(1, 4).add(new Paragraph(vo.getSyszd())).setVerticalAlignment(VerticalAlignment.MIDDLE);
            table.addCell(sydLabel);
            table.addCell(sydValue);

            //第8行
            Cell phoneLabel = new Cell().add(new Paragraph("联系方式")).setBold().setHeight(25).setVerticalAlignment(VerticalAlignment.MIDDLE);
            String phone = vo.getMobile();
            if (phone == null) {
                phone = "无";
            }
            Cell phoneValue = new Cell(1, 7).add(new Paragraph(phone)).setVerticalAlignment(VerticalAlignment.MIDDLE);
            table.addCell(phoneLabel);
            table.addCell(phoneValue);

            //第9行
            Cell resumeLabel = new Cell().add(new Paragraph("个人简历")).setBold().setHeight(120).setVerticalAlignment(VerticalAlignment.MIDDLE);
            String resume = vo.getResume();
            if (resume == null) {
                resume = "无";
            }
            Cell resumeValue = new Cell(1, 7).add(new Paragraph(resume)).setHeight(120).setVerticalAlignment(VerticalAlignment.MIDDLE);
            table.addCell(resumeLabel);
            table.addCell(resumeValue);

            // 第10行
            Cell workExperienceAndSocialPracticeLabel = new Cell().add(new Paragraph("工作经历与社会实践")).setBold().setHeight(150).setVerticalAlignment(VerticalAlignment.MIDDLE);
            String workExperienceAndSocialPractice = vo.getResume();
            if (workExperienceAndSocialPractice == null) {
                workExperienceAndSocialPractice = "无";
            }
            Cell workExperienceAndSocialPracticeValue = new Cell(1, 7).add(new Paragraph(workExperienceAndSocialPractice)).setHeight(150).setVerticalAlignment(VerticalAlignment.MIDDLE);
            table.addCell(workExperienceAndSocialPracticeLabel);
            table.addCell(workExperienceAndSocialPracticeValue);

            // 第11行
            Cell awardsAndRelevantCertificatesLabel = new Cell().add(new Paragraph("获奖情况与相关证书")).setBold().setHeight(150).setVerticalAlignment(VerticalAlignment.MIDDLE);
            String awardsAndRelevantCertificates = vo.getResume();
            if (awardsAndRelevantCertificates == null) {
                awardsAndRelevantCertificates = "无";
            }
            Cell awardsAndRelevantCertificatesValue = new Cell(1, 7).add(new Paragraph(awardsAndRelevantCertificates)).setHeight(150).setVerticalAlignment(VerticalAlignment.MIDDLE);
            table.addCell(awardsAndRelevantCertificatesLabel);
            table.addCell(awardsAndRelevantCertificatesValue);

            //学号行
            Cell xh = new Cell(1,8).add(new Paragraph("学号："+vo.getXh())).setHeight(20).setMarginRight(40).setTextAlignment(TextAlignment.RIGHT).setBorder(Border.NO_BORDER);
            table.addCell(xh);

            // 第12行
            Cell mainScientificResearchAchievementsAndAcademicActivitiesLabel = new Cell().add(new Paragraph("主要科研成果和学术活动")).setBold().setHeight(140).setVerticalAlignment(VerticalAlignment.MIDDLE);
            String mainScientificResearchAchievementsAndAcademicActivities = vo.getResume();
            if (mainScientificResearchAchievementsAndAcademicActivities == null) {
                mainScientificResearchAchievementsAndAcademicActivities = "无";
            }
            Cell mainScientificResearchAchievementsAndAcademicActivitiesValue = new Cell(1, 7).add(new Paragraph(mainScientificResearchAchievementsAndAcademicActivities)).setMinHeight(140).setVerticalAlignment(VerticalAlignment.MIDDLE);
            table.addCell(mainScientificResearchAchievementsAndAcademicActivitiesLabel);
            table.addCell(mainScientificResearchAchievementsAndAcademicActivitiesValue);

            //第13行
            Cell selfPromotionAndJobSearchWillingnessLabel = new Cell().add(new Paragraph("个人自荐和求职意愿")).setBold().setHeight(120).setVerticalAlignment(VerticalAlignment.MIDDLE);
            String selfPromotionAndJobSearchWillingness = vo.getResume();
            if (selfPromotionAndJobSearchWillingness == null) {
                selfPromotionAndJobSearchWillingness = "无";
            }
            Cell selfPromotionAndJobSearchWillingnessValue = new Cell(1, 7).add(new Paragraph(selfPromotionAndJobSearchWillingness)).setMinHeight(120).setVerticalAlignment(VerticalAlignment.MIDDLE);
            table.addCell(selfPromotionAndJobSearchWillingnessLabel);
            table.addCell(selfPromotionAndJobSearchWillingnessValue);

            //第14行
            Cell menterReviewCommentLabel = new Cell(3,1).add(new Paragraph("导师推荐意见")).setBold().setWidth(5).setHeight(130).setVerticalAlignment(VerticalAlignment.MIDDLE);
            table.addCell(menterReviewCommentLabel);
            Cell menterReviewCommentValue = new Cell(1,7).add(new Paragraph("")).setMinHeight(100).setBorderBottom(Border.NO_BORDER).setVerticalAlignment(VerticalAlignment.MIDDLE);
            table.addCell(menterReviewCommentValue);

            Cell collegePhoneValue = new Cell(1,7).add(new Paragraph("导师签名：").setMarginRight(90)).setHeight(20).setBorderTop(Border.NO_BORDER).setBorderBottom(Border.NO_BORDER).setTextAlignment(TextAlignment.RIGHT).setVerticalAlignment(VerticalAlignment.MIDDLE);
            table.addCell(collegePhoneValue);

            SimpleDateFormat formatDate = new SimpleDateFormat("yyyy年MM月dd日");
            String menterReviewtDate = "   年  月  日";
            Cell menterReviewDateValue = new Cell(1,7).add(new Paragraph(menterReviewtDate).setMarginRight(90)).setHeight(20).setBorderTop(Border.NO_BORDER).setBorderLeft(Border.NO_BORDER).setTextAlignment(TextAlignment.RIGHT).setVerticalAlignment(VerticalAlignment.MIDDLE);
            table.addCell(menterReviewDateValue);

            //第15行
            Cell collegeCommentLabel = new Cell(1,4).add(new Paragraph("学院推荐意见")).setBold().setHeight(20).setVerticalAlignment(VerticalAlignment.MIDDLE).setBorderBottom(Border.NO_BORDER).setTextAlignment(TextAlignment.LEFT);
            table.addCell(collegeCommentLabel);

            Cell schoolCommentLabel = new Cell(1,4).add(new Paragraph("学校推荐意见")).setBold().setHeight(20).setVerticalAlignment(VerticalAlignment.MIDDLE).setBorderBottom(Border.NO_BORDER).setTextAlignment(TextAlignment.LEFT);
            table.addCell(schoolCommentLabel);

            String collegeComment = "无";
            if(vo.getStatus() == RECOMMENDATION_STATUS_PASS){
                collegeComment = vo.getReviewComment();
            }

            String collegeRecommendationDate = "无";
            Date collegeRecommendationTime = vo.getReviewTime();
            if (collegeRecommendationTime != null) {
                collegeRecommendationDate = formatDate.format(collegeRecommendationTime);
            }

            String spaces = String.join("", Collections.nCopies(5, "\u00A0"));

            Cell collegeCommentValue = new Cell(1,4).add(new Paragraph(collegeComment).add("\n").add("\n")
                    .add(spaces).add("学院盖章").add("\n")
                    .add(spaces).add(collegeRecommendationDate).add("\n").add("\n")
                    .add(spaces).add("联系电话：" + vo.getCollegePhone())).setHeight(115).setBorderTop(Border.NO_BORDER).setBorderBottom(Border.NO_BORDER);
            table.addCell(collegeCommentValue);

            String schoolComment = "请交由学院审核！";
            if(vo.getStatus() == RECOMMENDATION_STATUS_PASS){
                schoolComment = "同意！";
            }

            String schoolRecommendationDate = "无";
            Date schoolRecommendationTime = vo.getSchoolRecommendationTime();
            if (schoolRecommendationTime != null) {
                schoolRecommendationDate = formatDate.format(schoolRecommendationTime);
            }
            Cell schoolCommentValue = new Cell(1,4).add(new Paragraph(schoolComment).add("\n").add("\n")
                    .add(spaces).add("就业指导服务中心盖章").add("\n")
                    .add(spaces).add(schoolRecommendationDate).add("\n").add("\n")
                    .add(spaces).add("联系电话：027-88386093")).setHeight(115).setBorderTop(Border.NO_BORDER).setBorderBottom(Border.NO_BORDER);
            if(vo.getStatus() == RECOMMENDATION_STATUS_PASS){
                addSeal(schoolCommentValue);
            }
            table.addCell(schoolCommentValue);

            // 备注
            String space = String.join("", Collections.nCopies(3, "\u00A0"));

            Paragraph bz = new Paragraph().add("备注：1、本表仅供本校全日制普通高等学校毕业研究生就业推荐使用；").add("\n")
                    .add(space).add("2、毕业研究生学习成绩见“中南财经政法大学硕士研究生成绩单”").add("\n")
                    .add(space).add("3、用人单位若同意录用，应要求毕业生出具《毕业生就业协议书》，签署就业协议，学校将依据就业协议签发《就业报到证》。");
            Cell bzValue = new Cell(1,8).add(bz).setHeight(120).setTextAlignment(TextAlignment.LEFT).setVerticalAlignment(VerticalAlignment.MIDDLE);
            table.addCell(bzValue);

            document.add(table);
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    private void addCellTOTable(Table table,String label, String value, PdfFont font){
        table.addCell(new Cell().add(new Paragraph(label)).setMinHeight(40).setFont(font).setBold().setVerticalAlignment(VerticalAlignment.MIDDLE));
        table.addCell(new Cell().add(new Paragraph(value)).setMinHeight(40).setFont(font).setVerticalAlignment(VerticalAlignment.MIDDLE));
    }

    private void addSeal(Cell cell) {
        try{

            ImageData sealData = ImageDataFactory.create(pdfPicture + "recommendationSeal.jpg");
            Image sealImage = new Image(sealData);

            BackgroundPosition backgroundPosition = new BackgroundPosition().setPositionX(BackgroundPosition.PositionX.CENTER).setPositionY(BackgroundPosition.PositionY.TOP);
            BackgroundRepeat.BackgroundRepeatValue backgroundRepeatValue = BackgroundRepeat.BackgroundRepeatValue.NO_REPEAT;
            BackgroundRepeat backgroundRepeat = new BackgroundRepeat(backgroundRepeatValue, backgroundRepeatValue);
            BackgroundSize backgroundSize = new BackgroundSize();
            backgroundSize.setBackgroundSizeToValues(
                    UnitValue.createPointValue(Utilities.millimetersToPoints(35)),
                    UnitValue.createPointValue(Utilities.millimetersToPoints(35))
            );
            // 创建 BackgroundImage（关键修正）
            BackgroundImage backgroundImage = new BackgroundImage.Builder()
                    .setImage(sealImage.getXObject())  // 传递 Image 对象
                    .setBackgroundPosition(backgroundPosition)  // 图片居中
                    .setBackgroundRepeat(backgroundRepeat)  // 不重复平铺
                    .setBackgroundSize(backgroundSize)
                    .build();
            cell.setBackgroundImage(backgroundImage);
        } catch (IOException e) { e.printStackTrace(); }
    }
}
